package cn.tedu.sp06.fb;

import cn.tedu.web.util.JsonResult;
import org.springframework.cloud.netflix.zuul.filters.route.FallbackProvider;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.stereotype.Component;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * @author 金帮嘉诚 @date 2021-09-13 星期一 11:36
 */
@Component
public class ItemFB implements FallbackProvider {
    /**
     * @param
     * @return
     * @author 金帮嘉诚
     * @date 2021/9/13 11:43
     * 业务需求: 返回一个serviceId, 表示当前降级类是针对哪个后台服务的降级类
     * item-service只对该服务降级
     * * 全部服务
     * null 等价于*
     */
    @Override
    public String getRoute() {
        return "item-service";
    }

    @Override
    public ClientHttpResponse fallbackResponse(String route, Throwable cause) {
        return new ClientHttpResponse() {
            @Override// 状态 包括状态码和信息
            public HttpStatus getStatusCode() throws IOException {
                return HttpStatus.INTERNAL_SERVER_ERROR;
            }

            @Override// RawStatusCode 原始状态码
            public int getRawStatusCode() throws IOException {
                return HttpStatus.INTERNAL_SERVER_ERROR.value();
            }

            @Override// 状态文本
            public String getStatusText() throws IOException {
                return HttpStatus.INTERNAL_SERVER_ERROR.getReasonPhrase();
            }

            @Override
            public void close() {

            }

            @Override
            public InputStream getBody() throws IOException {
                // JsonResult --- {code:500, msg:xxx, data:null}
                String s = JsonResult.err().code(500).msg("调用后台服务出错").toString();
                return new ByteArrayInputStream(s.getBytes());
            }

            @Override
            public HttpHeaders getHeaders() {
                HttpHeaders headers = new HttpHeaders();
                headers.add("Content-Type", "application/json;charset=UTF-8");
                return headers;
            }
        };
    }
}
